﻿var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var types = {
    "css": "text/css",
    "gif": "image/gif",
    "html": "text/html",
    "ico": "image/x-icon",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "js": "text/javascript",
    "json": "application/json",
    "pdf": "application/pdf",
    "png": "image/png",
    "svg": "image/svg+xml",
    "swf": "application/x-shockwave-flash",
    "tiff": "image/tiff",
    "txt": "text/plain",
    "wav": "audio/x-wav",
    "wma": "audio/x-ms-wma",
    "wmv": "video/x-ms-wmv",
    "xml": "text/xml",
	"unknown":"text/plain"
};
http.createServer(function (req, res) {
	var pathname = url.parse(req.url).pathname;
    var realPath = __dirname + (pathname=='/' ? '/login.html':pathname);
    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';
	console.log(ext);
    path.exists(realPath, function (exists) {
        if (!exists) {
            res.writeHead(404, {
                'Content-Type': 'text/plain'
            });
 
            res.write("This req URL " + pathname + " was not found on this server.");
            res.end();
        } else {
            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    res.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
 
                    res.end(err);
                } else {
                    res.writeHead(200, {
                        'Content-Type':'text/html'
                    });
 
                   var contentType = types[ext];
                    res.writeHead(200, {'Content-Type': contentType});
                    res.write(file, "binary");
                    res.end();
                }
            });
        }
    });
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');